package com.webwork.mood.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final String TIMEOUT_STR = "操作超时，请重新登陆！";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean tage = true;
		if (null == request.getSession(true).getAttribute("user")) {
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				System.out.println(request.getRequestURI() + " no login for ajax.");
				response.sendError(401, LoginInterceptor.TIMEOUT_STR);

			} else {
				System.out.println(request.getRequestURI() + " no login for page.");
				request.setAttribute("reset_login", LoginInterceptor.TIMEOUT_STR);
				request.setAttribute("requestURI", request.getRequestURI());
				request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
			}
			tage = false;
		}
		System.out.println(request.getRequestURI() + " passed.");
		return tage;
	}

}
